package com.easylinkin.linkappapi.lobar.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.lobar.dto.CheckPeopleInfoDTO;
import com.easylinkin.linkappapi.lobar.dto.CheckRecordDTO;
import com.easylinkin.linkappapi.lobar.dto.OCRIdentifyDTO;
import com.easylinkin.linkappapi.lobar.entity.AppPeopleCheck;
import com.easylinkin.linkappapi.lobar.entity.vo.CheckRecordVo;
import com.easylinkin.linkappapi.lobar.mapper.LaborManagementMapper;
import com.easylinkin.linkappapi.lobar.service.LaborManagementService;
import com.easylinkin.linkappapi.lobar.util.IdentityUtils;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Pattern;

@Api(tags = "人员核查")
@RestController
@RequestMapping("/laborManagement")
public class LaborManagementController {

    @Autowired
    private LaborManagementService laborManagementService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Autowired
    private LaborManagementMapper laborManagementMapper;

    @GetMapping("/getPeopleInfo")
    @ApiOperation("获取检查人员信息")
    public RestMessage getPeopleInfo(CheckPeopleInfoDTO query) {
        Assert.notNull(query.getCardNo(), "身份证号不能为空");
        return laborManagementService.getPeopleInfo(query);
    }

    @PostMapping("/getCheckRecordList")
    @ApiOperation("获取核查记录列表")
    public RestMessage getCheckRecordList(@RequestBody RequestModel<CheckRecordDTO> query) {
        return laborManagementService.getCheckRecordList(query);
    }

    @PostMapping("/saveCheckRecord")
    @ApiOperation("保存核查记录")
    public RestMessage saveCheckRecord(@RequestBody AppPeopleCheck dto) {
//        Assert.notNull(dto.getPeopleName(), "姓名不能为空");
//        Assert.notNull(dto.getPeopleCompany(), "参建单位不能为空");
        if (dto.getCard() != null && !dto.getCard().isEmpty()) {
            Assert.isTrue(IdentityUtils.isLegalPattern(dto.getCard()), "身份证号非法");
        }
        if (dto.getTelephone() != null && !dto.getTelephone().isEmpty()) {
            boolean matches = Pattern.matches("^1[3-9]\\d{9}$", dto.getTelephone());
            Assert.isTrue(matches, "手机号非法");
        }
        return laborManagementService.saveCheckRecord(dto);
    }

    @GetMapping("/queryRecordDetail")
    @ApiOperation("获取核查记录明细")
    public RestMessage queryRecordDetail(String id) {
        return laborManagementService.queryRecordDetail(id);
    }

    @PostMapping("/deleteRecord")
    @ApiOperation("删除记录")
    public RestMessage deleteRecord(@RequestBody CheckRecordVo vo) {
        return laborManagementService.deleteRecord(vo);
    }

    @GetMapping("/queryCurState")
    @ApiOperation("获取人员最新状态")
    public RestMessage queryCurState(CheckPeopleInfoDTO query) {
        Assert.notNull(query.getCardNo(), "身份证号不能为空");
        return laborManagementService.queryCurState(query);
    }

    @PostMapping("/dealCheckRecord")
    @ApiOperation("处理核查记录")
    public RestMessage dealCheckRecord(@RequestBody AppPeopleCheck dto) {
        Assert.notNull(dto.getDealResult(), "处理结果不能为空");
        return laborManagementService.dealCheckRecord(dto);
    }

    @PostMapping("/export")
    @ApiOperation("核查记录导出")
    @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "核查记录导出")
    public void export(@RequestBody RequestModel<CheckRecordDTO> requestModel, HttpServletRequest request, HttpServletResponse response) {
        IPage<CheckRecordVo> page = new Page(-1, -1);
        //项目id 过滤
        if (null != linkappUserContextProducer.getCurrent()) {
            requestModel.getCustomQueryParams().setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
        List<CheckRecordVo> checkRecordList = laborManagementMapper.getCheckRecordList(requestModel.getCustomQueryParams(), page);
        checkRecordList.forEach(item ->{
            item.setStatus(item.getStatus().equals("0") ? "待处理": "已处理");
            if (item.getCheckIn() == null) {
                item.setCheckIn("未登记");
            } else {
                item.setCheckIn(item.getCheckIn().equals("0") ? "离场": "在场");
                if (item.getSafeEdu() != null) {
                    item.setSafeEdu(item.getSafeEdu().equals("0") ? "未进行" : "进行中");
                }
                item.setAge(item.getAge().equals("0") ? "未超龄" : "超龄");
                item.setAttendance(item.getAttendance().equals("0") ? "出勤正常" : "连续未出勤");
            }
            switch (item.getDealRequire()) {
                case "0":
                    item.setDealRequire("信息补录");
                    break;
                case "1":
                    item.setDealRequire("清退场");
                    break;
                case "2":
                    item.setDealRequire("无需处理");
                    break;
                default:
                    break;
            }
        });
        String keyValue = "处理状态:status,姓名:peopleName,身份证号:cardNo,单位:peopleCompany,检查结果(实名制登记):checkIn,检查结果(安全教育):safeEdu," +
                "检查结果(人员年龄):age,检查结果(人员出勤):attendance,处理要求:dealRequire,记录人:recordPeople,核查时间:checkTime,处理人:dealName,处理时间:dealTime";
        String title = "人员考核记录";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, checkRecordList, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @PostMapping("/getCount")
    @ApiOperation("数量统计")
    public RestMessage getCount(@RequestBody CheckRecordDTO dto) {
        return laborManagementService.getCount(dto);
    }

    @PostMapping("/ocrIdentify")
    @ApiOperation("OCR身份证识别")
    public RestMessage ocrIdentify(@RequestBody OCRIdentifyDTO dto) throws Exception {
        Assert.notNull(dto.getPicCode(), "图片信息不能为空");
        return laborManagementService.ocrIdentify(dto);
    }

    @GetMapping("/getPeopleList")
    @ApiOperation("获取人员列表")
    public RestMessage getPeopleList(CheckPeopleInfoDTO query) {
        Assert.notNull(query.getUserInfo(), "姓名/身份证号不能为空");
        return laborManagementService.getPeopleList(query);
    }

}
